
import request from '../utils/request.js'

async function login(btn) {
    const usernameInput = document.getElementById('username')
    const passwordInput = document.getElementById('password')
    
    const username = usernameInput.value
    const password = passwordInput.value
    
    if (username.trim() === '' || password.trim() === '') {
        showToast('用户名或密码不能为空！', 'error')
        return
    }

    btn.classList.add('loading')
    btn.disabled = true
    
    const config = {
        method: 'get',
        url: '/user/login',
        params: {
            username: username,
            password:password
        }
    }

    try {
        const response = await request(config)
        localStorage.setItem('isLoggedIn', 'true')
        //localStorage.setItem('isAdmin', 'false')
        localStorage.setItem('currentUser', username)
        

        showToast('登录成功！', 'success')
        
        setTimeout(() => {
            window.location.href = 'home.html'
        },1000)
        
        
    } catch (error) {
        //console.log(JSON.stringify(error))
        showToast(`${error.msg}`, 'error')

    } finally {
        btn.classList.remove('loading')
        btn.disabled=false
    }
    
}

function switchType(type, event) {
    if (type === 'admin') {
        localStorage.setItem('isAdmin','true')
    } else {
        localStorage.setItem('isAdmin','false')
    }
    const btns = document.querySelectorAll('.type-btn')
    btns.forEach(btn => btn.classList.remove('active'))
    event.target.classList.add('active')

    const username = document.getElementById('username')
    const password = document.getElementById('password')
    
    username.style.transition = 'all 0.3s'
    password.style.transition = 'all 0.3s'


}

window.login = login
window.switchType = switchType

